/**
 * File : UDPServer.java Author : R. Scheurer (EIA-FR) Date : 04.10.2012
 *
 * Description - a simple UDP server template
 *
 */
package sockets.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;

// A class that implements the UDP server's behaviour
public class UDPServer {

    static final int MAX_SIZE = 100; // The maximum size of a message
                                     // that can be recieved
    static final int SERVER_PORT = 1234; // The UDP server's port number

    // The program's entry point, starting the server.
    public static void main(String[] args) {
        try {
            // We create the datagram socket
            InetAddress thisIp = InetAddress.getLocalHost();
            DatagramSocket s = new DatagramSocket(SERVER_PORT, thisIp);
            // We display the server's informations in the console
            System.out.println("Starting UDP server with IP = "
                    + thisIp.getHostAddress() + ":" + SERVER_PORT);
            // Fo each UDP packet we recieve, we print its data in the console
            while (true) {
                byte[] buffer = new byte[MAX_SIZE];
                String message = "";
                SocketAddress sa = s.getLocalSocketAddress();
                // We initilize and assign the packet to be recieved.
                DatagramPacket dp = new DatagramPacket(buffer, MAX_SIZE, sa);
                s.receive(dp);
                // For every byte int the data section, we store 
                // the corresponding character in the message string.
                for (byte b : dp.getData()) {
                    message += (char) b;
                }
                // We print the message and it's source.
                System.out.println("Message from " + dp.getAddress()
                        + ":" + dp.getPort() + " : " + message);
            }
        } catch (IOException e) {
            System.err.println("UDP connection failed. Aborting...");
            System.exit(1);
        }
    }
}
